import Vue from 'vue';
import PopupVue from './popup';

const PopupConstructor = Vue.extend(PopupVue);

const popupPool = [];
const getAnInstance = () => {
  if (popupPool.length > 0) {
    const instance = popupPool[0];
    popupPool.splice(0, 1);
    return instance;
  }

  return new PopupConstructor({
    el: document.createElement('div')
  });
};

const returnAnInstance = (instance) => {
  if (instance) {
    popupPool.push(instance);
  }
};

// 重写close回调
PopupConstructor.prototype.close = function () {
  this.visible = false;
  returnAnInstance(this);
};

const Popup = function (options) {
  if (typeof options === 'string') {
    options = {
      message: options
    };
    if (arguments[1]) {
      options.type = arguments[1];
    }
    if (arguments[2]) {
      options.duration = arguments[2];
    }
  } else if(!options) {
    options = {};
  }
  const instance = getAnInstance();
  const defaultOptions = {
    type: 'default',
    message: '',
    duration: 3000
  };

  options = Object.assign({}, defaultOptions, options);
  Object.keys(options).forEach((key) => {
    instance[key] = options[key];
  });

  clearTimeout(instance.timer);

  const duration = options.duration;

  function show(resolve) {
    document.body.appendChild(instance.$el);

    Vue.nextTick(() => {
      instance.visible = true;
      if (duration) {
        instance.timer = setTimeout(() => {
          instance.close();
          if (resolve) {
            resolve();
          }
        }, duration);
      }
    });
  }

  // duration 为0的时候，返回实例，不为0时，返回Promise
  if (duration) {
    // 返回 Promise 回调
    return new Promise((resolve, reject) => {
      show(resolve);
    });
  }

  show();
  return instance;
};

Popup.success = (msg) => {
  return Popup({
    type: 'success',
    message: msg
  });
};

Popup.error = (msg) => {
  return Popup({
    type: 'error',
    message: msg
  });
};

Popup.warn = (msg) => {
  return Popup({
    type: 'warn',
    message: msg
  });
};

export default Popup;
